//
//  LXHandleDatas.m
//  LXLocationRelated
//
//  Created by Livespro on 2017/10/22.
//  Copyright © 2017年 Livesxu. All rights reserved.
//

#import "LXHandleDatas.h"
#import "LXMonitorDatas.h"
#import "LXDistanceDescription.h"
#import "LXMotionDescription.h"
#import "LXLocationDistances.h"

#import <CoreMotion/CoreMotion.h>
#import <CoreLocation/CoreLocation.h>

@implementation LXHandleDatas

+ (instancetype)shareHandle{
    
    static LXHandleDatas *handle = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        handle = [[LXHandleDatas alloc]init];
        
    });
    return handle;
}

- (instancetype)init{
    self = [super init];
    if (self) {
        
//        NSArray *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//        NSString *path = [docPath objectAtIndex:0];
//        NSString *filePath = [path stringByAppendingPathComponent:@"LXRealm"];
//        NSLog(@"数据库目录 = %@",filePath);
//
//        RLMRealmConfiguration *config = [RLMRealmConfiguration defaultConfiguration];
//        config.fileURL = [NSURL URLWithString:filePath];
//        config.readOnly = NO;
//        int currentVersion = 1.0;
//        config.schemaVersion = currentVersion;
//
////        config.migrationBlock = ^(RLMMigration *migration , uint64_t oldSchemaVersion) {
////            // 这里是设置数据迁移的block
////            if (oldSchemaVersion < currentVersion) {
////            }
////        };
////
//        [RLMRealmConfiguration setDefaultConfiguration:config];
        
    }
    return self;
}

/**
 写入路程
 */
- (void)handleDistanceIn:(CLLocation *)startLocation;{
    
    if ([self judgeDistanceJoin:startLocation]) {//如果衔接则不开新的行程记录
        
        return;
    }
    
    LXLocationDistances *distance = [[LXLocationDistances alloc]init];
    
    NSNumber *bgrSign = (NSNumber *)[[NSUserDefaults standardUserDefaults] objectForKey:@"APPBackGroundRun"];
    
    distance.backGround = bgrSign.boolValue;
    
    distance.userId = @"01";
    
    distance.locationStart = [NSDate date];
    
    distance.distanceId = (NSInteger)[distance.locationStart timeIntervalSince1970];//取此值作为行程id
    
    [[NSUserDefaults standardUserDefaults] setObject:@(distance.distanceId) forKey:@"kLastDistanceId"];//存储最后一次记录的行程id
    
    distance.locationEnd = distance.locationStart;
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        RLMRealm *realm = [RLMRealm defaultRealm];
        [realm transactionWithBlock:^{
            [realm addObject: distance];
        }];
    });
}


/**
 判断是否衔接行程 100m 5分钟

 @return bool
 */
- (BOOL)judgeDistanceJoin:(CLLocation *)startLocation{
    
    NSDate *beforeEndTime = [[NSUserDefaults standardUserDefaults] objectForKey:@"kLastDistanceEndTime"];
    if (!beforeEndTime) {
        
        return NO;
    }
    NSTimeInterval differTime = [[NSDate date] timeIntervalSinceDate:beforeEndTime];
    
    if (differTime < 60*5) {
        
        return YES;
    }
    
    NSArray *beforeEndLocationArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"kLastDistanceLocation"];
    if (!beforeEndLocationArray) {
        
        return NO;
    }
    NSNumber *latitudeN = beforeEndLocationArray.lastObject;
    NSNumber *longitudeN = beforeEndLocationArray.firstObject;
    CLLocation *beforeEndLocation = [[CLLocation alloc]initWithLatitude:latitudeN.floatValue longitude:longitudeN.floatValue];
    
    CLLocationDistance differDistance = [startLocation distanceFromLocation:beforeEndLocation];
    if (differDistance < 100) {
        
        return YES;
    }
    
    return NO;
}

/**
 行程结束
 */
- (void)handleDistanceEnd:(CLLocation *)endLocation;{
    
    NSNumber *distanceId = [[NSUserDefaults standardUserDefaults] objectForKey:@"kLastDistanceId"];
    
    [[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:@"kLastDistanceEndTime"];//存储最后一次行程结束的时间
    [[NSUserDefaults standardUserDefaults] setObject:@[@(endLocation.coordinate.longitude),@(endLocation.coordinate.latitude)] forKey:@"kLastDistanceLocation"];//存储最后一次行程结束的位置
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        RLMRealm *realm = [RLMRealm defaultRealm];
        //createOrUpdateInRealm：withValue：这个方法是增量更新的,需要主键
        [realm beginWriteTransaction];
        [LXLocationDistances createOrUpdateInRealm:realm withValue:@{@"distanceId":distanceId,@"locationEnd":[[NSUserDefaults standardUserDefaults] objectForKey:@"kLastDistanceEndTime"]}];
        [realm commitWriteTransaction];
    });
}

/**
 删除行程

 @param distanceId 行程id
 */
- (void)handleDistanceDelete:(NSInteger)distanceId;{
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"distanceId == %ld",distanceId];
    RLMResults *distances = [LXLocationDistances objectsWithPredicate:predicate];
    
    RLMRealm *realm = [RLMRealm defaultRealm];
    // 在事务中删除
    [realm beginWriteTransaction];
    [realm deleteObjects:distances];
    [realm commitWriteTransaction];
    
}

/**
 行程导出
 */
- (NSString *)handleDistanceOut;{
    
    RLMResults *monitorDatas = [LXLocationDistances allObjects];// 从默认的 Realm 数据库中
    
    NSMutableString *monitorStr = [NSMutableString string];
    for (LXLocationDistances *data in monitorDatas) {
        
        NSString *dataStr = [NSString stringWithFormat:@"%@ %@\n",data.locationStart,data.locationEnd];
        
        [monitorStr appendString:dataStr];
    }
    return monitorStr;
}

- (void)handleLocationInfoLatitude:(double)latitude
                         longitude:(double)longitude
                          altitude:(double)altitude
                horizontalAccuracy:(double)horizontalAccuracy
                  verticalAccuracy:(double)verticalAccuracy
                            course:(double)course
                             speed:(double)speed
                         timestamp:(NSDate *)timestamp
                       trueHeading:(double)trueHeading
                   headingAccuracy:(double)headingAccuracy;{
    
    LXDistanceDescription *disDesc = [[LXDistanceDescription alloc]init];
    
    disDesc.latitude = latitude;
    disDesc.longitude = longitude;
    disDesc.altitude = altitude;
    disDesc.horizontalAccuracy = horizontalAccuracy;
    disDesc.verticalAccuracy = verticalAccuracy;
    disDesc.course = course;
    disDesc.speed = speed;
    disDesc.timestamp = timestamp;
    disDesc.trueHeading = trueHeading;
    disDesc.headingAccuracy = headingAccuracy;
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        RLMRealm *realm = [RLMRealm defaultRealm];
        [realm transactionWithBlock:^{
            [realm addObject: disDesc];
        }];
    });
}

/**
 location数据读取
 
 @param timeStart 开始时间
 @param endTime 结束时间
 */
- (NSString *)handleLocationOutStart:(NSDate *)timeStart End:(NSDate *)endTime;{
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"timestamp >= %@ AND timestamp <= %@",
                         timeStart,endTime];
    RLMResults *distances = [LXDistanceDescription objectsWithPredicate:predicate];
    
    NSMutableString *distanceStr = [NSMutableString string];
    for (LXDistanceDescription *data in distances) {
        
        NSString *dataStr = [NSString stringWithFormat:@"%.6f %.6f speed %.2f\n",data.latitude,data.longitude,data.speed];
        
        [distanceStr appendString:dataStr];
    }
    return distanceStr;
}

/**
 location数据删除
 
 @param timeStart 开始时间
 @param endTime 结束时间
 */
- (void)handleLocationDeleteStart:(NSDate *)timeStart End:(NSDate *)endTime;{
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"timestamp >= %@ AND timestamp <= %@",
                              timeStart,endTime];
    RLMResults *distances = [LXDistanceDescription objectsWithPredicate:predicate];
    
    RLMRealm *realm = [RLMRealm defaultRealm];
    // 在事务中删除
    [realm beginWriteTransaction];
    [realm deleteObjects:distances];
    [realm commitWriteTransaction];
}

/**
 motion传感器信息写入
 
 @param deviceMotion 传感器model
 */
- (void)handleMotionInfoMotion:(CMDeviceMotion *)deviceMotion;{
    
    LXMotionDescription *motion = [[LXMotionDescription alloc]init];
    
    motion.pitch = deviceMotion.attitude.pitch;
    motion.roll = deviceMotion.attitude.roll;
    motion.yaw = deviceMotion.attitude.yaw;
    
    motion.accelerationX = deviceMotion.userAcceleration.x;
    motion.accelerationY = deviceMotion.userAcceleration.y;
    motion.accelerationZ = deviceMotion.userAcceleration.z;
    
    motion.gravityX = deviceMotion.gravity.x;
    motion.gravityY = deviceMotion.gravity.y;
    motion.gravityZ = deviceMotion.gravity.z;
    
    motion.gyroscopeX = deviceMotion.rotationRate.x;
    motion.gyroscopeY = deviceMotion.rotationRate.y;
    motion.gyroscopeZ = deviceMotion.rotationRate.z;
    
    motion.magneticFieldX = deviceMotion.magneticField.field.x;
    motion.magneticFieldY = deviceMotion.magneticField.field.y;
    motion.magneticFieldZ = deviceMotion.magneticField.field.z;
    
    motion.timestamp = [NSDate date];
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        RLMRealm *realm = [RLMRealm defaultRealm];
        [realm transactionWithBlock:^{
            [realm addObject: motion];
        }];
    });
}

/**
 motion数据读取
 
 @param timeStart 开始时间
 @param endTime 结束时间
 */
- (NSString *)handleMotionOutStart:(NSDate *)timeStart End:(NSDate *)endTime;{
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"timestamp >= %@ AND timestamp <= %@",
                              timeStart,endTime];
    RLMResults *motions = [LXMotionDescription objectsWithPredicate:predicate];
    
    NSMutableString *motionStr = [NSMutableString string];
    for (LXMotionDescription *data in motions) {
        
        NSString *dataStr = [NSString stringWithFormat:@"%.6f %.6f %.6f time %@\n",data.roll,data.pitch,data.yaw,data.timestamp];
        
        [motionStr appendString:dataStr];
    }
    return motionStr;
}

/**
 motion数据删除
 
 @param timeStart 开始时间
 @param endTime 结束时间
 */
- (void)handleMotionDeleteStart:(NSDate *)timeStart End:(NSDate *)endTime;{
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"timestamp >= %@ AND timestamp <= %@",
                              timeStart,endTime];
    RLMResults *motions = [LXMotionDescription objectsWithPredicate:predicate];
    
    RLMRealm *realm = [RLMRealm defaultRealm];
    // 在事务中删除
    [realm beginWriteTransaction];
    [realm deleteObjects:motions];
    [realm commitWriteTransaction];
}

//日志写入
- (void)handleMonitorIn:(NSString *)descMonitor
                   Time:(NSDate *)timestamp
                   User:(NSString *)userId;{
    
    LXMonitorDatas *monitorData = [[LXMonitorDatas alloc]init];
    
    monitorData.descMonitor = descMonitor;
    monitorData.timestamp = timestamp;
    monitorData.userId = userId;
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        RLMRealm *realm = [RLMRealm defaultRealm];
        [realm transactionWithBlock:^{
            [realm addObject: monitorData];
        }];
    });
}

/**
 日志读取
 
 @return 读取内容
 */
- (NSString *)handleMonitorOut;{
    
    RLMResults *monitorDatas = [LXMonitorDatas allObjects];// 从默认的 Realm 数据库中
    
    NSMutableString *monitorStr = [NSMutableString string];
    for (LXMonitorDatas *data in monitorDatas) {
        
        NSString *dataStr = [NSString stringWithFormat:@"%@ %@\n",data.descMonitor,data.timestamp];
        
        [monitorStr appendString:dataStr];
    }
    return monitorStr;
}

@end
